package cc.ilzy.mall.utils;

import cc.ilzy.mall.dto.LoginUserDTO;
import cc.ilzy.mall.exceptions.ExceptionEnum;
import cc.ilzy.mall.exceptions.MallException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class JWTUtils {
    private static final int EXPIRE = 7; // 7天
    private static final String SECRET = "ilzy_mall_secret"; // 密钥
    private static final String ISSUER = "ilzy"; // 签发者
    private static final String SUBJECT = "ilzy_mall_token"; // 主题

    /**
     * 生成JWT
     *
     * @param userDTO
     * @return
     */
    public static String generateJsonWebToken(LoginUserDTO userDTO) {
        if (userDTO == null) {
            throw new MallException(ExceptionEnum.GENERATE_TOKEN_ERROR);
        }
        // 生成JWT的逻辑
        // 使用EXPIRE, SECRET, ISSUER, SUBJECT等常量来创建JWT
        // 返回生成的JWT字符串
        String token = JWT.create()
                          .setIssuer(ISSUER)
                          .setSubject(SUBJECT)
                          .setPayload("id", userDTO.getId())
                          .setPayload("name", userDTO.getName())
                          .setPayload("mail", userDTO.getMail())
                          .setPayload("headImg", userDTO.getHeadImg())
                          .setIssuedAt(DateUtil.date())
                          .setExpiresAt(DateUtil.offsetDay(DateUtil.date(), EXPIRE))
                          .setKey(SECRET.getBytes(StandardCharsets.UTF_8))
                          .sign();
        return token; // 这里需要实现JWT生成逻辑
    }

    /**
     * 验证JWT
     * @param token
     * @return
     */
    public static JWTPayload checkJWT(String token) {
        if (token == null || token.isEmpty()) {
            throw new MallException(ExceptionEnum.TOKEN_NOT_EXIST);
        }
        // 解析JWT的逻辑
        // 如果解析失败或验证不通过，抛出MallException
        JWT jwt = null;
        try {
            jwt = JWT.of(token);
            jwt.setKey(SECRET.getBytes(StandardCharsets.UTF_8));
            if (!jwt.validate(0)) {
                throw new MallException(ExceptionEnum.TOKEN_INVALID);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new MallException(ExceptionEnum.TOKEN_INVALID);
        }

        log.info("token:{}", jwt.getPayload());
        JWTPayload payload = jwt.getPayload();
        return payload;
    }
}
